<?php

/**
 * Created by PhpStorm.
 * User: sqq
 * Date: 2018/08/11
 * Time: 10:35
 */
class ApiServiceCardOrderController extends BaseController{
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 10:03:32
     * @Description: 套餐卡订单列表
     */
    public function cardOrderList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $service_card_order = ServiceCardOrder::leftJoin('service_card_base','service_card_base.id','=','service_card_order.service_card_id')
                ->select([
                    'service_card_order.order_id',
                    'service_card_order.amount',
                    'service_card_order.pay_amount',
                    'service_card_order.created_at',
                    'service_card_order.pay_type',
                    'service_card_order.status',
                    'service_card_base.name',

                ])
                ->where('service_card_order.user_id',$wechat_user->id)
                ->orderBy('service_card_order.created_at','desc')
                ->get();
            foreach($service_card_order as $v){
                $v->amount = bcdiv($v->amount,100,2);
                $v->pay_amount = bcdiv($v->pay_amount,100,2);
                $v->status_value = Orders::$service_card_status[$v->status];
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $service_card_order,
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "cardOrderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 10:28:20
     * @Description: 套餐卡订单详情
     */
    public function cardOrderDetails(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $card_order = ServiceCardOrder::where('order_id',Input::get('order_id'))
                ->where('user_id',$wechat_user->id)
                ->first();
            if(!empty($card_order)){
                $card_order->status_value = Orders::$service_card_status[$card_order->status];
                $card_order->pay_type_value = isset($card_order->pay_type)?Orders::$paytype[$card_order->pay_type]:"";
                $card_order->amount = bcdiv($card_order->amount,100,2);
                $card_order->pay_amount = bcdiv($card_order->pay_amount,100,2);
                $card_order->shop_name = MaintenanceShops::where('id',$card_order->shop_id)->pluck('name');
                $pay_record = ServiceCardOrderPayRecord::where('order_id',$card_order->order_id)->where('status',1)->get();
                if(!empty($pay_record)){
                    foreach($pay_record as $v){
                        $v->amount = bcdiv($v->amount,100,2);
                    }
                }
                $card_order->pay_order_record = $pay_record;
                $card_order->service_card_base = ServiceCardBase::where('id',$card_order->service_card_id)->first();
                if(!empty($card_order->service_card_base)){
                    $card_order->service_card_base->amount = bcdiv($card_order->service_card_base->amount,100,2);
                }
                $base_pack = ServiceCardBasePack::where('service_card_base_id',$card_order->service_card_id)->get();
                if(!empty($base_pack)){
                    foreach($base_pack as $v){
                        $v->amount = bcdiv($v->amount,100,2);
                        $v->pack_name = ProductPackage::where('id',$v->pack_id)->pluck('name');
                    }
                }
                $card_order->service_card_base_puck = $base_pack;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $card_order
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "cardOrderDetails", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 15:34:18
     * @Description: 取消未支付套餐卡订单
     */
    public function cardOrderCancel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            try{
                $card_order = ServiceCardOrder::find(Input::get('order_id'));
                if(!in_array($card_order->status,Orders::$to_be_confirmed)){
                    $response = Lang::get("error.service_card_order_remove_error_95008");
                    break;
                }
                $card_order->status = 1010;
                $card_order->save();

                $order_flows = new ServiceCardOrderFlow();
                $order_flows->order_id = $card_order->order_id;
                $order_flows->status = $card_order->status;
                $order_flows->user_id = $wechat_user->id;
                $order_flows->type = 'custom';
                $order_flows->save();
            }catch (Exception $e){
                Log::error("error", array("system" => "api3.0" ,"event" => "cardOrderCancel", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.service_card_order_remove_error_95008");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "cardOrderCancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 17:16:20
     * @Description: 套餐卡详情
     */
    public function cardDetail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required'
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $card_detail = ServiceCardDetail::with(['serviceCardBase','serviceCardDetailPack'])
                ->where('user_id',$wechat_user->id)
                ->where('id',Input::get('id'))
                ->first();
            if(is_null($card_detail)){
                $response = Lang::get("error.service_card_base_error_95000");
                break;
            }
            if(!empty($card_detail->serviceCardBase)){
                $card_detail->service_card_base->amount = bcdiv($card_detail->service_card_base->amount,100,2);
                $shop_name = array();
                if($card_detail->service_card_base->limit_shop == 1){
                    $shop_name[]['name'] = MaintenanceShops::where('id',$card_detail->shop_id)->pluck('name');
                }else{
                    $service_card_base_shop = ServiceCardBaseShop::where('service_card_base_id', $card_detail->service_card_base->id)->where('status',1)->get();
                    foreach($service_card_base_shop as $v){
                        $shop_name[]['name'] = MaintenanceShops::where('id',$v->shop_id)->pluck('name');
                    }
                }
                if($card_detail->service_card_base->date_type == 1){
                    $begin_date = $card_detail->get_time;
                    $end_date = $card_detail->end_date;
                }else{
                    $begin_date = $card_detail->service_card_base->begin_date;
                    $end_date = $card_detail->service_card_base->end_date;
                }
                $card_detail->get_time = date("Y-m-d",strtotime($begin_date));
                $card_detail->end_date = date("Y-m-d",strtotime($end_date));
                $status_value = '';
                if(strtotime($end_date) < time()){
                    $status_value = '已过期';
                }

                $card_detail->status_value = $status_value;
                $scdp = ServiceCardDetailPack::where('service_card_detail_id',$card_detail->id)->where('service_card_base_id',$card_detail->service_card_base->id)->select('curr_number')->get();
                $i = 0;
                foreach($scdp as $v){
                    $i += $v->curr_number;
                }
                $card_detail->curr_number = $i;
            }
            if(!empty($card_detail->serviceCardDetailPack)){
                foreach($card_detail->service_card_detail_pack as $v){
                    $v->amount = bcdiv($v->amount,100,2);
                    $v->pack_name = ProductPackage::where('id',$v->pack_id)->pluck('name');
                    $small_icon = ProductPackage::where('id',$v->pack_id)->pluck('small_icon');
                    $v->pack_img = empty($small_icon)?"":Config::get('config.product_img').$small_icon;
                }
            }
            $card_detail->shop_name = isset($shop_name)?$shop_name:array();
            $card_detail->car = ServiceCardCar::where('user_id',$card_detail->user_id)->where('status',1)->get();
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $card_detail,
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "cardDetail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-03 11:49:40
     * @Description: 绑定车辆
     * @link： http://www.activity.com/wechat/api3.0/bindCar?token=668c155fab8dd6ef1e789b33ff6d040e&short_name=%E4%BA%AC&car_no=A111111
     */
    public function bindCar(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'short_name' => 'required',
                'car_no' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $source = 0;
            $unbund_source = 0;
            if(Input::get('source')){
                $source = Input::get('source');
                $unbund_source = Input::get('unbund_source');
            }else{
                $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
                if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
                    $source = 1;
                    $unbund_source = 1;
                }
                if(strpos($agent, 'android')){
                    $source = 2;
                    $unbund_source = 2;
                }
            }

            $short_name = Input::get('short_name');
            $car_no = Input::get('car_no');

            DB::beginTransaction();
            try{
                $service_card = ServiceCard::where('user_id',$wechat_user->id)->first();
                if(empty($service_card)){
                    $service_card = new ServiceCard();
                    $service_card->account_no = date("YmdHis",time()).Common::createOrderId();
                    $service_card->user_id = $wechat_user->id;
                    $service_card->save();
                }
                //ServiceCardCar::where('user_id',$wechat_user->id)->where('status',1)->where('account_no',$service_card->account_no)->update(array('status'=>0,'unbund_source'=>$unbund_source,'unbund_at'=>Common::currentTimeString(),'op_by'=>$wechat_user->id));
                //foreach($car_no as $v){
                    if(empty($short_name) || empty($car_no)){
                        continue;
                    }

                    $res = ServiceCardCar::where('user_id',$wechat_user->id)->where('status',1)->where('car_no',$short_name.$car_no)->first();
                    if(!empty($res)){
                        $response = Lang::get("error.car_not_exit_error_11000");
                        break;
                    }
                    $service_card_car = new ServiceCardCar();
                    $service_card_car->user_id = $wechat_user->id;
                    $service_card_car->account_no = $service_card->account_no;
                    $service_card_car->car_no = $short_name.$car_no;
                    $service_card_car->status = 1;
                    $service_card_car->created_by = $wechat_user->id;
                    $service_card_car->source = $source;
                    $service_card_car->save();
                //}
                DB::commit();
            }catch(Exception $e){
                DB::rollBack();
                Log::error("error", array("system" => "api3.0" ,"event" => "bindCar", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.data_save_error_30001");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "bindCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-03 11:49:40
     * @Description: 绑定车辆列表
     * @link：
     */
    public function bindCarList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $car = ServiceCardCar::where('user_id',$wechat_user->id)->where('status',1)->get();
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $car
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "bindCarList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-08-11 10:35:32
     * @Description: 套餐余量
     * @retuen $status_value [0-已过期 1-即将到期 2-正常]
     * @link: http://www.activity.com/wechat/api3.0/service_card/cardAllowance?token=668c155fab8dd6ef1e789b33ff6d040e
     */
    public function cardAllowance(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }

            $page = Input::get('page',1);
            $page_size = Input::get('page_size',15);

            $scd=ServiceCardDetail::where('user_id',$wx_user->id)->where('status',2)->where("end_date",">=",date("Y-m-d",time()))->get();//找到该用户的正常的能用的套餐卡
            $finally_arr=array();
            foreach ($scd as $_scd) {
                $scdp=ServiceCardDetailPack::leftJoin("product_package","product_package.id","=","service_card_detail_pack.pack_id")->where("service_card_detail_pack.service_card_detail_id",$_scd->id)->where("service_card_detail_pack.curr_number",">",0)
                   ->select("service_card_detail_pack.curr_number","product_package.id","product_package.name","service_card_detail_pack.service_card_detail_id")->get(); //套餐卡里面所有有效的服务

                foreach ($scdp as $_scdp) {
                    if(isset($finally_arr[$_scdp->id])){
                        $t_scdp=$finally_arr[$_scdp->id];
                        $t_scdp->curr_number=$t_scdp->curr_number+$_scdp->curr_number;
                        $finally_arr[$_scdp->id]=$t_scdp;
                    }else{
                        $finally_arr[$_scdp->id]=$_scdp;
                    }
                    //$sch = ServiceCardBasePack::join('service_card_detail','service_card_base_pack.service_card_base_id','=','service_card_detail.service_card_base_id')->where('service_card_base_pack.pack_id',42)->where('service_card_detail.user_id',$wx_user->id)->get();
                }
            }

            if(!is_null($finally_arr)){
                foreach($finally_arr as $_key => $_val){
                    $sch = ServiceCardBasePack::join('service_card_detail','service_card_base_pack.service_card_base_id','=','service_card_detail.service_card_base_id')->where('service_card_base_pack.pack_id',$_val->id)->where('service_card_detail.user_id',$wx_user->id)->get(); //用户购买的服务对应的所有套餐卡
                    if(!is_null($sch)){
                        $status_value = '2'; //正常
                        foreach($sch as $_k => $_v){
//                            if (in_array($_v->pack_id, [73,39, 44, 45, 72])) {
//                                continue;
//                            }

                            $scb = ServiceCardBase::where('id', $_v->service_card_base_id)->first(); //套餐卡基本信息
                            if(!is_null($scb)) {
                               // print_r($_v);die;
                                if ($scb->date_type == 1) {
                                    $begin_date = $_v->get_time;
                                    $end_date = $_v->end_date;
                                } else {
                                    $begin_date = $scb->begin_date;
                                    $end_date = $scb->end_date;
                                }
                                if (strtotime($end_date) < time()) {
                                    $status_value = '0';   //已过期
                                }
                                if (strtotime($end_date) - time() < 30 * 24 * 3600 && strtotime($_val->end_date) - time() > 0) {
                                    $status_value = '1'; //即将过期
                                }
                            }
                        }
                        $_val->status_value = $status_value;
                        //die;
                    }
                }
            }
            $finally_arr = array_slice($finally_arr, ($page-1)*$page_size, $page_size);
            $temp_arr=array("count"=>sizeof($finally_arr),"phone"=>$wx_user->phone,"service_package"=>array_values($finally_arr));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "/service_card/cardAllowance", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-08-11 17:37:32
     * @Description: 套餐余量——明细
     * @link: http://www.activity.com/wechat/api3.0/service_card/cardAllowanceShow?token=668c155fab8dd6ef1e789b33ff6d040e&pack_id=42
     */
    public function cardAllowanceShow(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
                'pack_id'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }

            //获取参数
            $pack_id = Input::get('pack_id');
            $page = Input::get('page',1);
            $page_size = Input::get('page_size',15);
            $sch = ProductPackage::where('id',$pack_id)->select('id','name')->first();

            //先调用产品接口，查找当前门店产品id的集合。
            $ids = ServiceCardBasePack::shopPackIds('',$wx_user->id,$pack_id);
            $sql_struct = "select %s "
                . " from service_card_detail a "
                . "left join service_card_detail_pack as b on b.service_card_detail_id = a.id "
                . "left join  service_card_base c on a.service_card_base_id=c.id "
                . "where b.id in ($ids) and a.status=2";
            $count = DB::select(sprintf($sql_struct," count(a.id) count"));
            $sql = sprintf($sql_struct,"a.id,c.id as bid,c.name,a.status,c.user_status,b.number,b.curr_number,a.end_date,a.get_time");
            $list = DB::select($sql);



            if(!is_null($list)){
                $sch->z_curr_number = '0';
                foreach($list as $_key => $_val){
                    $status_value = '2';
                    $scb = ServiceCardBase::where('id', $_val->bid)->first(); //套餐卡基本信息
                    if(!is_null($scb)) {
                        // print_r($_v);die;
                        $_val->shops = ServiceCardBaseShopUse::join('maintenance_shops','service_card_base_shop_use.shop_id','=','maintenance_shops.id')->where('service_card_base_id',$_val->bid)->where('maintenance_shops.status',1)->where('service_card_base_shop_use.status',1)->select('maintenance_shops.id','name')->get();
                        $sch->z_curr_number += $_val->curr_number;
                        if (strtotime($_val->end_date) < time()) {
                            $status_value = '0';   //已过期
                            $sch->z_curr_number = $sch->z_curr_number - $_val->curr_number;
                            array_splice($list,$_key,1);
                        }
                        if (strtotime($_val->end_date) - time() < 30 * 24 * 3600 && strtotime($_val->end_date) - time() > 0) {
                            $status_value = '1'; //即将过期
                        }
                        if($_val->curr_number == 0){
                            //array_splice($list,$_key,1);
                            unset($list[$_key]);
                        }
                    }
                    $_val->status_value = $status_value;
                }
                $list = array_slice($list, ($page-1)*$page_size, $page_size);
            }

            $temp_arr=array("phone"=>$wx_user->phone,'pack'=>$sch,"list"=>$list);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "/service_card/cardAllowanceShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-08-11 17:37:32
     * @Description: 套餐余量——消费记录列表
     * @link: http://www.activity.com/wechat/api3.0/service_card/ServiceCardUseList?token=668c155fab8dd6ef1e789b33ff6d040e
     */
    public function ServiceCardUseList(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }

            //获取参数
            $pack_id = Input::get('pack_id');
            $page = Input::get('page',1);
            $page_size = Input::get('page_size',15);
            $time = Input::get('time',0);
            if($time == 0){
                $end_time = date("Y-m-d H:i:s",time());
                $start_time = date("Y-m-d",strtotime('-2 month'))." 00:00:00";
            }else {
                $start_time = date($time . "-01-01 00:00:00");
                $end_time = date($time . "-12-31 00:00:00");
            }
            $scd=ServiceCardDetail::where('user_id',$wx_user->id)->where('status',2)->where("end_date",">=",date("Y-m-d",time()))->get();//找到该用户的正常的能用的套餐卡
            $finally_arr = [];
            $month = [];

            $id = $scd;
            $id = $id->toArray();
            $detail_id = array();
            foreach($id as $k_id => $v_id){
                $detail_id[] = $v_id['id'];
            }
            //查询用户已经使用信息
            $temp = ServiceCardConsumption::whereIn('service_card_detail_id',$detail_id)->where('service_card_consumption_record.status', 1)->where('service_card_consumption_record.updated_at','>=',$start_time)->where('service_card_consumption_record.updated_at','<=',$end_time)->get()->toArray();
            if(!empty($temp)) {
                $res = [];
                $cousumption = [];
                foreach ($temp as $t => $tmp) {
                    if ($tmp['type'] == 0) {
                        $type = Orders::where('order_id', $tmp['order_id'])->select('order_type')->first();
                        if ($type->order_type == 1) {
                            $res[$t]['types'] = 0;
                        } else {
                            $res[$t]['types'] = 2;
                        }
                        $product_id = OrderProduct::where('id', $tmp['product_id'])->where('status', 1)->first();
                        $res[$t]['product_id'] = $product_id->product_id;
                    } else {
                        $res[$t]['types'] = $tmp['type'];
                        $product_id = CarWashOrder::where('order_id', $tmp['order_id'])->first();
                        $res[$t]['product_id'] = $product_id->producd_id;
                    }
                    $table = $tmp['type'] == 1 ? 'car_wash_order' : 'orders';
                    $order_sql = "select b.shop_id,c.name from $table b left join maintenance_shops c on b.shop_id=c.id where b.order_id = " . $tmp['order_id'];
                    $order_info = DB::select($order_sql);
                    $res[$t]['shop_id'] = $order_info[0]->shop_id;
                    $res[$t]['name'] = $order_info[0]->name;
                    $res[$t]['updated_at'] = $tmp['updated_at'];
                    $res[$t]['order_id'] = $tmp['order_id'];
                }

                if(!is_null($scd)){
                    foreach ($scd as $_scd) {  //->where("service_card_detail_pack.curr_number",">",0)
                        $scdp=ServiceCardDetailPack::leftJoin("product_package","product_package.id","=","service_card_detail_pack.pack_id")->where("service_card_detail_pack.service_card_detail_id",$_scd->id)
                            ->select("service_card_detail_pack.curr_number","product_package.id","product_package.name","service_card_detail_pack.service_card_detail_id")->get(); //套餐卡里面所有有效的服务



                        foreach ($scdp as $_scdp) {
                            if(isset($finally_arr[$_scdp->id])){
                                $t_scdp=$finally_arr[$_scdp->id];
                                $t_scdp->curr_number=$t_scdp->curr_number+$_scdp->curr_number;
                                $finally_arr[$_scdp->id]=$t_scdp;
                            }else{
                                $finally_arr[$_scdp->id]=$_scdp;
                            }
                            //$sch = ServiceCardBasePack::join('service_card_detail','service_card_base_pack.service_card_base_id','=','service_card_detail.service_card_base_id')->where('service_card_base_pack.pack_id',42)->where('service_card_detail.user_id',$wx_user->id)->get();
                        }

                        if(!is_null($finally_arr)){
                            foreach($finally_arr as $k =>$v){
                                $ids = ServiceCardBasePack::shopPackIds('',$wx_user->id,$v->id);
                                $sql_struct = "select %s "
                                    . " from service_card_detail a "
                                    . "left join service_card_detail_pack as b on b.service_card_detail_id = a.id "
                                    . "left join  service_card_base c on a.service_card_base_id=c.id "
                                    . "where b.id in ($ids) and a.status<>1";
                                $count = DB::select(sprintf($sql_struct," count(a.id) count"));
                                $sql = sprintf($sql_struct,"a.id,c.id as bid,c.name,a.status,c.user_status,b.number,b.curr_number,a.end_date");
                                $v->list = DB::select($sql);


                                if(!is_null($v->list)){

                                    if(!empty($res)){
                                        $cousumption = [];
                                        foreach($res as $w){
                                            if($w['product_id'] == $v->id){
                                                $cousumption[] = $w;
                                            }
                                        }
                                        $v->cousumption = $cousumption;
                                        $v->use_number = count($cousumption);
                                        if(!empty($v->cousumption)){
                                            foreach($v->cousumption as $_k){
                                                //print_r($v->cousumption);die;
                                                //foreach($_v as $month_k => $month_v){
                                                $month[] = $_k['updated_at'];
                                                //}
                                            }
                                        }else{
                                            unset($finally_arr[$k]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
//            $month_time = [];
//            if(!empty($month)){
//                foreach($month as $m => $mon){
//                    $rs = gmdate("Y", strtotime($mon));
//                    if(!$month_time){
//                        $month_time[] = [
//                            'id' => $rs,
//                            'name' =>$rs
//                        ];
//                    }else{
//                        foreach($month_time as $mont_key => $mont_val){
//                            if(!in_array($rs,$mont_val)){
//                                $month_time[] = [
//                                    'id' => $rs,
//                                    'name' =>$rs
//                                ];
//                            }
//                        }
//                    }
//                }
//            }
//            $re = [
//                'id' => '0',
//                'name' =>'近三个月'
//            ];
//            array_unshift($month_time,$re);

            //$temp_arr=array("phone"=>$wx_user->phone,"list"=>$finally_arr,'month' => $month_time);
            $temp_arr=array("phone"=>$wx_user->phone,"list"=>$finally_arr);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "/service_card/ServiceCardUseList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-08-11 17:37:32
     * @Description: 套餐余量——消费记录列表
     * @link: http://www.activity.com/wechat/api3.0/service_card/month?token=668c155fab8dd6ef1e789b33ff6d040e
     */
    public function month(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }

            //获取参数
            $pack_id = Input::get('pack_id');
            $page = Input::get('page',1);
            $page_size = Input::get('page_size',15);
            $time = Input::get('time',0);
            if($time == 0){
                $end_time = date("Y-m-d H:i:s",time());
                $start_time = date("Y-m-d",strtotime('-2 month'))." 00:00:00";
            }else {
                $start_time = date($time . "-01-01 00:00:00");
                $end_time = date($time . "-12-31 00:00:00");
            }
            //$scd=ServiceCardDetail::where('user_id',$wx_user->id)->where('status',2)->where("end_date",">=",date("Y-m-d",time()))->get();//找到该用户的正常的能用的套餐卡
            $scd=ServiceCardDetail::where('user_id',$wx_user->id)->where('status',2)->get();
            $finally_arr = [];
            $month = [];

            $id = $scd;
            $id = $id->toArray();
            $detail_id = array();
            foreach($id as $k_id => $v_id){
                $detail_id[] = $v_id['id'];
            }
            //查询用户已经使用信息
            //$temp = ServiceCardConsumption::whereIn('service_card_detail_id',$detail_id)->where('service_card_consumption_record.status', 1)->where('service_card_consumption_record.updated_at','>=',$start_time)->where('service_card_consumption_record.updated_at','<=',$end_time)->get()->toArray();
            $temp = ServiceCardConsumption::whereIn('service_card_detail_id',$detail_id)->where('service_card_consumption_record.status', 1)->get()->toArray();
//            if(!empty($temp)) {
//                $res = [];
//                $cousumption = [];
//                foreach ($temp as $t => $tmp) {
//                    if ($tmp['type'] == 0) {
//                        $type = Orders::where('order_id', $tmp['order_id'])->select('order_type')->first();
//                        if ($type->order_type == 1) {
//                            $res[$t]['types'] = 0;
//                        } else {
//                            $res[$t]['types'] = 2;
//                        }
//                        $product_id = OrderProduct::where('id', $tmp['product_id'])->where('status', 1)->first();
//                        $res[$t]['product_id'] = $product_id->product_id;
//                    } else {
//                        $res[$t]['types'] = $tmp['type'];
//                        $product_id = CarWashOrder::where('order_id', $tmp['order_id'])->first();
//                        $res[$t]['product_id'] = $product_id->producd_id;
//                    }
//                    $table = $tmp['type'] == 1 ? 'car_wash_order' : 'orders';
//                    $order_sql = "select b.shop_id,c.name from $table b left join maintenance_shops c on b.shop_id=c.id where b.order_id = " . $tmp['order_id'];
//                    $order_info = DB::select($order_sql);
//                    $res[$t]['shop_id'] = $order_info[0]->shop_id;
//                    $res[$t]['name'] = $order_info[0]->name;
//                    $res[$t]['updated_at'] = $tmp['updated_at'];
//                    $res[$t]['order_id'] = $tmp['order_id'];
//                }
//
//                if(!is_null($scd)){
//                    foreach ($scd as $_scd) {  //->where("service_card_detail_pack.curr_number",">",0)
//                        $scdp=ServiceCardDetailPack::leftJoin("product_package","product_package.id","=","service_card_detail_pack.pack_id")->where("service_card_detail_pack.service_card_detail_id",$_scd->id)
//                            ->select("service_card_detail_pack.curr_number","product_package.id","product_package.name","service_card_detail_pack.service_card_detail_id")->get(); //套餐卡里面所有有效的服务
//
//
//
//                        foreach ($scdp as $_scdp) {
//                            if(isset($finally_arr[$_scdp->id])){
//                                $t_scdp=$finally_arr[$_scdp->id];
//                                $t_scdp->curr_number=$t_scdp->curr_number+$_scdp->curr_number;
//                                $finally_arr[$_scdp->id]=$t_scdp;
//                            }else{
//                                $finally_arr[$_scdp->id]=$_scdp;
//                            }
//                            //$sch = ServiceCardBasePack::join('service_card_detail','service_card_base_pack.service_card_base_id','=','service_card_detail.service_card_base_id')->where('service_card_base_pack.pack_id',42)->where('service_card_detail.user_id',$wx_user->id)->get();
//                        }
//
//                        if(!is_null($finally_arr)){
//                            foreach($finally_arr as $k =>$v){
//                                $ids = ServiceCardBasePack::shopPackIds('',$wx_user->id,$v->id);
//                                $sql_struct = "select %s "
//                                    . " from service_card_detail a "
//                                    . "left join service_card_detail_pack as b on b.service_card_detail_id = a.id "
//                                    . "left join  service_card_base c on a.service_card_base_id=c.id "
//                                    . "where b.id in ($ids) and a.status<>1";
//                                $count = DB::select(sprintf($sql_struct," count(a.id) count"));
//                                $sql = sprintf($sql_struct,"a.id,c.id as bid,c.name,a.status,c.user_status,b.number,b.curr_number,a.end_date");
//                                $v->list = DB::select($sql);
//
//
//                                if(!is_null($v->list)){
//
//                                    if(!empty($res)){
//                                        $cousumption = [];
//                                        foreach($res as $w){
//                                            if($w['product_id'] == $v->id){
//                                                $cousumption[] = $w;
//                                            }
//                                        }
//                                        $v->cousumption = $cousumption;
//
//                                        if(!empty($v->cousumption)){
//                                            foreach($v->cousumption as $_k){
//                                                //print_r($v->cousumption);die;
//                                                //foreach($_v as $month_k => $month_v){
//                                                $month[] = $_k['updated_at'];
//                                                //}
//                                            }
//                                        }else{
//                                            unset($finally_arr[$k]);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            $month_time = [];
            $a = [];
            if(!empty($temp)){
                foreach($temp as $k => $v){
                    $rs = gmdate("Y", strtotime($v['updated_at']));
                    if($month_time) {
                        $a = array_column($month_time,'id');
                        if(!in_array($rs,$a)){
                            $month_time[] = [
                                'id' => $rs,
                                'name' =>$rs."年"
                            ];
                        }
                    }else{
                        $month_time[] = [
                            'id' => $rs,
                            'name' =>$rs."年"
                        ];
                    }
                }
            }
            //die;
//            if(!empty($month)){
//                foreach($month as $m => $mon){
//                    $rs = gmdate("Y", strtotime($mon));
////                    if(!$month_time){
////                        $month_time[] = [
////                            'id' => $rs,
////                            'name' =>$rs."年"
////                        ];
////                    }else{
////                        foreach($month_time as $mont_key => $mont_val){
////                            if(!in_array($rs,$mont_val)){
////                                $month_time[] = [
////                                    'id' => $rs,
////                                    'name' =>$rs."年"
////                                ];
////                            }
////                        }
////                    }
//
//
            $re = [
                'id' => '0',
                'name' =>'三个月内'
            ];
            array_unshift($month_time,$re);

            $temp_arr=array("phone"=>$wx_user->phone,'month' => $month_time);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "/service_card/ServiceCardUseList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}